package com.lepu.pcecg500;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lepu.pcecg500.BloodLipidHistoryAdapter;
import com.lepu.pcecg500.R;
import com.lepu.pcecg500.http.EcgHttpBean;
import com.lepu.pcecg500.http.HttpDataBean;
import com.lepu.pcecg500.http.HttpResultBean;
import com.lepu.pcecg500.http.HttpUrl;
import com.lepu.pcecg500.util.Constant;
import com.lepu.pcecg500.util.EcgTable;
import com.lepu.pcecg500.util.FinalDbManager;
import com.lepu.pcecg500.util.ImageTool;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.qqtheme.framework.picker.DatePicker;
import rxhttp.RxHttp;

/**
 * author : xiaoxin
 * date   : 2021/4/6 13:22
 * desc   : 血脂历史数据
 * update :
 */
public class ECGHistoryActivity extends Activity {

    private static final String TAG = "BloodLipidHistory";
    private RecyclerView rvHome;
    private LinearLayout llFinish;
    private TextView tvTitle;
    List<EcgTable> dataInfo = new ArrayList<>();
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private Button btClear;
    private TextView tvSeltime;
    private Button bt_submit;
    private Button bt_select_all;
    private BloodLipidHistoryAdapter adapter;
    private FinalDbManager finalDbManager;
    private String org_cold = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ecg_history);

        finalDbManager = FinalDbManager.getInstance(this);

        org_cold = SPUtils.getInstance()
                .getString("org_cold","");

        rvHome = findViewById(R.id.rv_home);
        llFinish = findViewById(R.id.ll_finish);
        tvTitle = findViewById(R.id.tv_title);
        tvSeltime = findViewById(R.id.tv_seltime);
        btClear = findViewById(R.id.bt_clear);
        bt_submit = findViewById(R.id.bt_submit);
        bt_select_all = findViewById(R.id.bt_select_all);

        bt_select_all.setVisibility(View.VISIBLE);

        bt_select_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bt_select_all.getText().toString().equals("全选")) {
                    for (int i = 0; i < dataInfo.size(); i++) {
                        dataInfo.get(i).setSelect(true);
                    }
                    adapter.notifyDataSetChanged();
                    bt_select_all.setText("反选");
                } else {
                    for (int i = 0; i < dataInfo.size(); i++) {
                        dataInfo.get(i).setSelect(false);
                    }
                    adapter.notifyDataSetChanged();
                    bt_select_all.setText("全选");
                }
            }
        });
        adapter = new BloodLipidHistoryAdapter(R.layout.item_blood_lipid_list, dataInfo);
        rvHome.setLayoutManager(new LinearLayoutManager(this));
        rvHome.setAdapter(adapter);

        initData();
        initListener();

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EcgTable bean = (EcgTable) adapter.getData().get(position);
                bean.setSelect(!bean.isSelect());
                adapter.notifyItemChanged(position);
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_item_chakan) {
                    try {
                        EcgTable bean = (EcgTable) adapter.getData().get(position);
                        bean.setSelect(!bean.isSelect());
                        adapter.notifyItemChanged(position);
                        loadEcgImageDialog(new File(bean.getPath()));
                    } catch (Exception e) {
                        ToastUtils.showLong("本地文件已删除，请从PC平台查看！");
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void loadEcgImageDialog(File url) {
        new XPopup.Builder(this)
                .asImageViewer(null, url, new SmartGlideImageLoader())
                .show();
    }

    private void initData() {
        tvTitle.setText("数据列表");
        String currentTime = TimeUtils.millis2String(new Date().getTime(),"yyyy-MM-dd");
        tvSeltime.setText(currentTime);
        selectDB(currentTime);
    }

    private void initListener() {
        llFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvSeltime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDateDialog();
            }
        });

        btClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNormalDialog();
            }
        });

        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSubmitlDialog();
            }
        });
    }

    private void showNormalDialog(){
        //创建dialog构造器
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        //设置title
        normalDialog.setTitle("提示");
        //设置icon
        normalDialog.setIcon(R.mipmap.logo);
        //设置内容
        normalDialog.setMessage("确定清除" + tvSeltime.getText().toString() + "的数据吗？");
        //设置按钮
        normalDialog.setPositiveButton(getString(R.string.dialog_btn_confirm_text)
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delData();
                        dialog.dismiss();
                    }
                });
        //创建并显示
        normalDialog.create().show();
    }

    private void showSubmitlDialog(){
        //创建dialog构造器
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        //设置title
        normalDialog.setTitle("提示");
        //设置icon
        normalDialog.setIcon(R.mipmap.logo);
        //设置内容
        normalDialog.setMessage("确定提交" + tvSeltime.getText().toString() + "的数据吗？");
        //设置按钮
        normalDialog.setPositiveButton(getString(R.string.dialog_btn_confirm_text)
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        submitData();
                        dialog.dismiss();
                    }
                });
        //创建并显示
        normalDialog.create().show();
    }

    private void submitData() {
        for (int i = 0; i < dataInfo.size(); i++) {
            EcgTable bloodLipidTable = dataInfo.get(i);
            if (bloodLipidTable.isSelect()) {
                requestHttp(bloodLipidTable);
            }
        }
    }

    private void requestHttp(EcgTable bloodLipidTable) {
        EcgHttpBean ecgHttpBean = new EcgHttpBean();
        ecgHttpBean.setCold(bloodLipidTable.getCode());
        ecgHttpBean.setHR(bloodLipidTable.getHr());
        ecgHttpBean.setXDdiagnosis(bloodLipidTable.getConclusion());
        ecgHttpBean.setDTime(bloodLipidTable.getAddDate());
        if (!TextUtils.isEmpty(bloodLipidTable.getPath())) {
            String base64 = ImageTool.imageToBase64(bloodLipidTable.getPath());
            ecgHttpBean.setPicBuf("data:image/png;base64," + base64);
        }

        HttpDataBean httpDataBean = new HttpDataBean();
        httpDataBean.setOrgCold(org_cold);
        httpDataBean.setQueryType("Check");
        httpDataBean.setData(ecgHttpBean);
        Log.e(TAG, "requestHttp: " + GsonUtils.toJson(httpDataBean) );
        RxHttp.postJson(HttpUrl.getHttpUrl() + HttpUrl.ecgUrl)
                .addAll(GsonUtils.toJson(httpDataBean))
                .asClass(HttpResultBean.class)
                .subscribe(resultBean -> {
                    ToastUtils.showShort(resultBean.getResponseMsg() + "");
                    LogUtils.e(resultBean);
                    if (resultBean.getResponseCode() == 200) {
                        bloodLipidTable.setState("0");
                        bloodLipidTable.setType("0");
                        updateDbData(bloodLipidTable);
                    }
                }, throwable -> {
                    ToastUtils.showShort(throwable.getMessage() + "");
                    LogUtils.e(throwable.getMessage());
                });
    }

    /**
     * 血脂数据保存到数据库:根据当天时间查询条形码是否存在，存在更新，不存在保存；一个条形码一天最多一条数据
     * @param bloodLipidTable 本次测量血脂数据
     */
    private void updateDbData(EcgTable bloodLipidTable) {
        try {
            String where = "code = '" + bloodLipidTable.getCode() + "' AND addTime = '" + bloodLipidTable.getAddTime() + "'";
            finalDbManager.updataInInfoDB(bloodLipidTable,where);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void delData() {
        String where = " addTime = '" + tvSeltime.getText().toString().trim() + "'";
        finalDbManager.deleteByWhere(EcgTable.class,where);
        ToastUtils.showShort("删除成功");
        dataInfo.removeAll(dataInfo);
        setAdapter();
    }

    private void showDateDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePicker picker = new DatePicker(ECGHistoryActivity.this);
        picker.setRange(1900, year);//年份范围
        picker.setSelectedItem(year, month + 1, day);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year2, String month2, String day2) {
                String selectDate = year2 + "-" + month2 + "-" + day2;
                tvSeltime.setText(selectDate);
                selectDB(selectDate);
            }
        });
        picker.show();
    }

    public void selectDB(String time) {
        dataInfo.removeAll(dataInfo);
        String where = " addTime='" + time + "'";
        List<EcgTable> bloodLipidTableList =
                FinalDbManager.getInstance(this).findAllByWhereInInfoDB(EcgTable.class,where);
        dataInfo.addAll(bloodLipidTableList);
        setAdapter();
    }

    private void setAdapter() {
        bt_select_all.setText("全选");
        adapter.setNewData(dataInfo);
    }

}
